using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyMes.Infrastructure;
using MyMES.IServices.WarehouseManagement.Codings;
using VOL.Entity.DomainModels;
using VOL.Core.Extensions;
using VOL.Core.Utilities;
using Microsoft.EntityFrameworkCore;
using MyMES.Services.WarehouseManagement.Codings.DTOs;

namespace MyMES.Services.WarehouseManagement.Codings
{
    public class CodingService : ICodingService
    {
        private readonly IBaseRepository<BarcodeManagement> _barcodemanagementRepo;

        public CodingService(IBaseRepository<BarcodeManagement> barcodemanagementRepo)
        {
            _barcodemanagementRepo = barcodemanagementRepo;
        }

        /// <summary>
        /// 获取条码管理列表
        /// </summary>
        /// <param name="queryDTO">查询参数</param>
        /// <returns>分页结果</returns>
        public async Task<BarcodeDTO> GetBarcodeListAsync(BarcodeDTO queryDTO)
        {
            var query = _barcodemanagementRepo.GetAll();

            // 应用筛选条件
            if (!string.IsNullOrEmpty(queryDTO.BarcodeType))
            {
                query = query.Where(x => x.BarcodeType == queryDTO.BarcodeType);
            }
            if (!string.IsNullOrEmpty(queryDTO.BusinessCode))
            {
                query = query.Where(x => x.BusinessCode.Contains(queryDTO.BusinessCode));
            }
            if (!string.IsNullOrEmpty(queryDTO.BusinessName))
            {
                query = query.Where(x => x.BusinessName.Contains(queryDTO.BusinessName));
            }

            // 获取总记录数
            queryDTO.Total = await query.CountAsync();

            // 应用分页
            queryDTO.Items = await query
                .Skip((queryDTO.PageIndex - 1) * queryDTO.PageSize)
                .Take(queryDTO.PageSize)
                .ToListAsync();

            return queryDTO;
        }

        /// <summary>
        /// 更新条码信息
        /// </summary>
        /// <param name="barcode">条码信息</param>
        /// <returns>更新结果</returns>
        public async Task<bool> UpdateBarcodeAsync(BarcodeManagement barcode)
        {
            if (barcode == null || barcode.Id == 0)
            {
                throw new ArgumentException("无效的条码信息");
            }

            var existing = await _barcodemanagementRepo.FindAsync(barcode.Id);
            if (existing == null)
            {
                throw new Exception("未找到指定条码");
            }

            // 更新属性
            existing.Barcode = barcode.Barcode;
            existing.BarcodeFormat = barcode.BarcodeFormat;
            existing.BarcodeType = barcode.BarcodeType;
            existing.BarcodeDesc = barcode.BarcodeDesc;
            existing.BusinessCode = barcode.BusinessCode;
            existing.BusinessName = barcode.BusinessName;
            existing.Status = barcode.Status;

            await _barcodemanagementRepo.UpdateAsync(existing);
            return true;
        }

        /// <summary>
        /// 获取条码类型列表
        /// </summary>
        /// <returns>条码类型列表</returns>
        public List<KeyValuePair<string, string>> GetBarcodeTypes()
        {
            return new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("qr", "QR码"),
                new KeyValuePair<string, string>("bar", "条形码")
            };
        }

        /// <summary>
        /// 生成条码图片URL
        /// </summary>
        private string GenerateBarcodeImageUrl(string content, string type)
        {
            // 使用在线API生成条码图片URL
            var baseUrl = "https://api.qrserver.com/v1/create-qr-code/";
            var size = "100x100";
            return $"{baseUrl}?size={size}&data={Uri.EscapeDataString(content)}";
        }

        /// <summary>
        /// 根据条码值获取完整的条码信息
        /// </summary>
        /// <param name="barcode">条码值</param>
        /// <returns>条码完整信息</returns>
        public async Task<BarcodeManagement> GetBarcodeDetailsByValueAsync(string barcode)
        {
            if (string.IsNullOrEmpty(barcode))
            {
                throw new ArgumentException("条码值不能为空");
            }

            var result = await _barcodemanagementRepo.GetAll()
                .FirstOrDefaultAsync(x => x.Barcode == barcode);

            if (result == null)
            {
                throw new Exception("未找到对应的条码信息");
            }

            return result;
        }
    }

    public class BarcodeSearchParams
    {
        public string BarcodeType { get; set; }
        public string BusinessCode { get; set; }
        public string BusinessName { get; set; }
        public int PageIndex { get; set; } = 1;
        public int PageSize { get; set; } = 10;
    }

    public class PageResult<T>
    {
        public int Total { get; set; }
        public List<T> Items { get; set; }
    }
} 